<template>
  <div class="depart-tree glo-content-area">
    <div class="newContent">
      <div class="li">
        <span class="title">{{$t('newDevices.site')}}</span>
        <!-- 管理员列表默认不要选择场所,getParent() -->
        <span class="subtitle" @click="showAdminList=true,getData()" v-if="allPermissions.administrator">{{$t('companyManagement.administrator')}}</span>
        <div class="dec">{{$t('newDevices.dec')}}</div>
        <Input v-model="searchKey" :placeholder="$t('companyManagement.pleaseEnter')" >
          <Icon type="ios-search" slot="suffix" @click="searchClick"/>
        </Input>
      </div>
      <div class="tab">
        <!-- <Button size="large" type="primary">全部</Button>
        <Button size="large" type="default">公共</Button>
        <Button size="large" type="dashed">独立</Button> -->
        <!-- <div class="item" :class="{active:activeIndex==0}" @click="">{{$t('newDevices.all')}}</div> -->
        <div class="item" :class="{active:activeIndex==0}" @click="changeIndex(0)">{{$t('newDevices.all')}}</div>
        <div class="item" :class="{active:activeIndex==1}" @click="changeIndex(1)">{{$t('newDevices.public')}}</div>
        <div class="item" :class="{active:activeIndex==2}" @click="changeIndex(2)">{{$t('newDevices.independence')}}</div>
      </div>
    </div>
    <!-- treeData -->
    <Tree
      ref="tree"
      :data="treeData1"
      :render="renderContent"
      @on-select-change="handleSelect"
    />

    <DepartEdit
      v-if="ifCreate"
      :parent-depart="parentDepartId"
      :edit-item="editItem"
      @close="closeCreate"
    />
    <DepartEdit
      v-if="ifUpdate"
      edit-type="update"
      :edit-item="editItem"
      @close="closeUpdate"
    />
    <DepartEdit
      v-if="ifSettingAdmin"
      edit-type="settingAdmin"
      :edit-item="editItem"
      @close="closeSettingAdmin"
    />
    <Modal
        v-model="showAdminList"
        :title="$t('newDevices.adminList')"
        class="modelStyle"
        >
        <div class="adminList">
          <div style="margin-bottom:20px">
            <span style="display:inline-block;margin-right:20px">{{$t('newDevices.site')}}</span>
            <Cascader style="width: 200px;display:inline-block" :data="recordTypes" v-model="recordType" 
              @on-change="handleChange1" :placeholder="$t('newDevices.selectSite')"
              @on-visible-change="" change-on-select>
            </Cascader>
          </div>
          <Table
            ref="table"
            class="list"
            :data="list"
            :columns="columns"
          />
          <Page
            class="glo-content-area glo-pagenation"
            :total="total"
            :pageSize="pageSize"
            show-sizer
            :current="page"
            show-total
            @on-change="changePage"
            @on-page-size-change="changeSize"
          />
          <!-- <i-button style="margin-top: 16px;" class="submit" type="primary"  @click="handleSubmit('formItem')">{{ $t("devicesCreate.devCreateSubmit")}}</i-button> -->
        </div>
        
        <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
import {
  mapState, mapMutations
} from 'vuex'
import {
  del,
} from '@/api/depart.js'
import {
  getSite,
  getParentArea,
  deleteOne,
  selectAreaUser
} from '@/api/newDevices.js'
// import {
//   getList,
// } from '@/api/company.js'
import DepartItem from './DepartItem'
import DepartEdit from './DepartEdit'
import UserListSettings from './UserListSettings'

export default {
  components: {
    DepartEdit,
    UserListSettings
  },
  data () {
    return {
      parentDepartId: '',
      ifCreate: false,
      ifUpdate: false,
      ifSettingAdmin: false,
      editItem: null,
      searchKey:'',
      activeIndex:0,
      data1:[],
      showAdminList:false,
      searchName:'',
      columns: [
        // { type: 'selection', width: 70 },
        {
          type: 'index',
          width: 60,
          indexMethod: this.$_index_method,
        },
        {
          title: this.$t('visitorsIndex.visitorsNameTable'),
          key: 'realName',
          width: 100,
        },
        {
          title: this.$t('newDevices.jurisdiction'),
          key: 'roleName',
        },
        {
          title: this.$t('newDevices.site'),
          key: 'areaName',
          render: (h, { row }) => {
            let label = '-'
            let btnLabel = '-'
            if (row.areaName) {
              // label = row.areaType+row.areaName
              label = row.areaName
            }
            if (row.areaType=='G') {
              // label = row.areaType+row.areaName
              btnLabel = this.$t('newDevices.public')
            }else{
              btnLabel = this.$t('newDevices.independence')
            }
            return h('div',[
              h(
              'Tag',
                {     
                      props: { color:row.areaType=='G'?'blue':'green' },
              },
               btnLabel
              ),
            h(
              'span',
               ' '+label
              ),
            
            ],)
            
          },
        },
        
        {
          title: this.$t('newDevices.dateTime'),
          key: 'period',
          width: 200,
          render: (h, { row }) => {
            let label = '-'
            if (row.dateType==1) {
              label = row.period
            }else{
              label = this.$t('newDevices.longTime')
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('loginIndex.loginPhone'),
          key: 'username',
        },
        
      ],
      total:0,
      page: 1,
      pageSize: 10,
      list: [],
      recordTypes: [],
      recordType: [],
      areaId:'',
      allPermissions:{
        settingAdmin:false,
        creatSite:false,
        staffDepartmentAddChildEdit:false,
        staffDepartmentAddChildDel:false,
        administrator:false,
      },
      user:JSON.parse(window.localStorage.getItem('user'))||'',
      firstItem:''
    }
  },
  computed: {
    ...mapState('depart', [
      'selectedDepart',
      // 'list',
    ]),
    treeData1 () {
      return this.generateTreeData(this.data1)
    },
    btnShow () {
      return this.$store.state.btnShow
    },
    // selectedDepartId: {
    //   get () {
    //     return this.selectedDepart
    //   },
    //   set (val) {
    //     console.log('lalal======', val)
    //     this.$store.commit('depart/setSelected', val)
    //   },
    // },
  },
  watch: {
    btnShow(){
      this.columns = [
        // { type: 'selection', width: 70 },
        {
          type: 'index',
          width: 60,
          indexMethod: this.$_index_method,
        },
        {
          title: this.$t('visitorsIndex.visitorsNameTable'),
          key: 'realName',
          width: 100,
        },
        {
          title: this.$t('newDevices.jurisdiction'),
          key: 'roleName',
        },
        {
          title: this.$t('newDevices.site'),
          key: 'areaName',
          render: (h, { row }) => {
            let label = '-'
            let btnLabel = '-'
            if (row.areaName) {
              // label = row.areaType+row.areaName
              label = row.areaName
            }
            if (row.areaType=='G') {
              // label = row.areaType+row.areaName
              btnLabel = this.$t('newDevices.public')
            }else{
              btnLabel = this.$t('newDevices.independence')
            }
            return h('div',[
              h(
              'Tag',
                {     
                      props: { color:row.areaType=='G'?'blue':'green' },
              },
               btnLabel
              ),
            h(
              'span',
               ' '+label
              ),
            
            ],)
            
          },
        },
        
        {
          title: this.$t('newDevices.dateTime'),
          key: 'period',
          width: 200,
          render: (h, { row }) => {
            let label = '-'
            if (row.dateType==1) {
              label = row.period
            }else{
              label = this.$t('newDevices.longTime')
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('loginIndex.loginPhone'),
          key: 'username',
        },
        
      ]
      // if(this.data1&&this.data1[0]&&this.data1[0].areaName==="新场所"){
      //   this.data1[0].areaName=this.$t('title.newSite')
      // }
      this.getSiteList()
      return this.$store.state.btnShow
    },
    // activeIndex:function (newQuestion, oldQuestion){
    //   console.log('activeIndex',newQuestion)
    //   if(newQuestion==0){
    //     sessionStorage.setItem('areaType', '0')
    //     this.$store.state.areaType = '0'
    //   }else if(newQuestion==1){
    //     sessionStorage.setItem('areaType', 'G')
    //     this.$store.state.areaType = 'G'
    //   }else if(newQuestion==2){
    //     sessionStorage.setItem('areaType', 'D')
    //     this.$store.state.areaType = 'D'
    //   }
    // } 
        
  },
  mounted () {
    this.getSiteList()
    this.getAllPermissions()
  },

  methods: {
    getAllPermissions(){
      let da=JSON.parse(window.localStorage.getItem('logo'))||[]
      da.map(v => {
        if(v.permission=='#newDevices'&&v.children){
          v.children.map(a=>{
            if(a.permission=='#site'&&a.children){
              a.children.map(c=>{
                if(c.permission=='#settingAdmin'&&c.checked==='true'){
                  this.allPermissions.settingAdmin=true
                } 
                if(c.permission=='#creatSite'&&c.checked==='true'){
                  this.allPermissions.creatSite=true
                } 
                if(c.permission=='#staffDepartmentAddChildEdit'&&c.checked==='true'){
                  this.allPermissions.staffDepartmentAddChildEdit=true
                } 
                if(c.permission=='#staffDepartmentAddChildDel'&&c.checked==='true'){
                  this.allPermissions.staffDepartmentAddChildDel=true
                } 
              })
            }
            if(a.permission=='#administrator'&&a.checked==='true'){
              this.allPermissions.administrator=true
            }
            
          })
        }
      });
    },
    renderContent (h, { root, node, data }) {
      return h(DepartItem, {
        props: { data ,allPermissions:this.allPermissions,firstItem:this.firstItem},
        on: { action: (name) => this.handleAction(name, data) },
      })
    },
    handleAction (name, depart) {
      switch (name) {
        case 'create':
          this.showCreate(depart)
          break
        case 'update':
          this.showUpdate(depart)
          break
        case 'del':
          this.handleDel(depart)
          break
        case 'settingAdmin':
          this.showSettingAdmin(depart)
          break
      }
    },
    handleSelect (arr, target) {
      // console.log(arr[0].id)arr为空页面会报错
      // if (arr.length == 0) return    
      // this.$store.commit('setSelectedNew',arr[0].departId )
      console.log('tableId',arr.length)
      if (arr.length ==0) {
        sessionStorage.setItem('tableId', '无')
        this.$store.state.tableId = '无'
        sessionStorage.setItem('areaType', '无')
        this.$store.state.areaType = '无'
        // !! hack代码，阻断组件本身反选
        this.$refs.tree.handleSelect(target.nodeKey)
      } else {
        sessionStorage.setItem('tableId', arr[0].id)
        this.$store.state.tableId = arr[0].id 
        sessionStorage.setItem('areaType', arr[0].areaType)
        this.$store.state.areaType = arr[0].areaType 
      }
      sessionStorage.setItem('departIdNew', arr[0].departId)
      sessionStorage.setItem('editItem', JSON.stringify(arr[0]))
      this.$emit('isAreaType',arr[0].areaType)
    },

    showCreate (depart) {
      this.editItem = depart
      this.parentDepartId = depart.id
      this.ifCreate = true
    },
    closeCreate (ifUpdated) {
      ifUpdated && this.getSiteList()
      this.parentDepartId = ''
      this.ifCreate = false
    },

    showUpdate (item) {
      this.editItem = item
      this.ifUpdate = true
    },
    closeUpdate (ifUpdated) {
      ifUpdated && this.getSiteList()
      this.ifUpdate = false
    },
    showSettingAdmin (depart) {
      this.showAdminList = false
      this.parentDepartId = depart.id
      this.editItem = depart
      this.ifSettingAdmin = true
      
    },
    closeSettingAdmin (ifUpdated) {
      // ifUpdated && this.getSiteList()
      this.ifSettingAdmin = false
    },
    generateTreeData (arr) {
      // console.log('generateTreeData=============', arr)
      const result = []
      for (let i = 0; i < arr.length; i += 1) {
        const item = arr[i]
        const treeItem = {
          ...item,
          expand: true,
        }
        if (i === 0 && !this.$store.state.tableId) {
          console.log('jinlaile12')
          
          treeItem.selected = true
          sessionStorage.setItem('tableId', treeItem.id)
          sessionStorage.setItem('editItem', JSON.stringify(arr[0]))
          sessionStorage.setItem('areaType', treeItem.areaType)
          // console.log('isAreaType')
          // this.$emit('isAreaType',arr[0].areaType)
          // console.log('isAreaType1')
          this.$store.state.tableId = arr[0].id
          this.$store.state.areaType = arr[0].areaType

          
        } else if (this.$store.state.tableId === treeItem.id) {
          treeItem.selected = true
        }
        if (item.children && item.children.length) {
          treeItem.children = this.generateTreeData(item.children)
        }
        result.push(treeItem)
      }
      return result.sort((prev, next) => {
        const pervOrder = prev.departOrder || 0
        const nextOrder = next.departOrder || 0
        return pervOrder - nextOrder
      })
    },
    
    async handleDel (item) {
      this.$Modal.confirm({
        title: this.$t('devicesListSettings.devListDel')+this.$t('newDevices.site'),
        content: this.$t('newDevices.delSiteTip1'),
        onOk: async () => {
          const { success } = await deleteOne({ id: item.id })
          if (success) {
            this.$Message.success(this.$t('versionIndex.verDelBtnSucc'))
            this.getSiteList()
          } else {
            this.$Message.error(this.$t('newDevices.delSiteTip'))
          }
        },
      })
    },

    searchClick(e){
      this.getSiteList()
    },
    async getSiteList(){
      let areaName
      if(this.searchKey==this.$t('title.newSite')){
        areaName="新场所"
      }else{
        areaName=this.searchKey
      }
      let data1={
        areaName,
        areaType:this.activeIndex==1?'G':this.activeIndex==2?'D':'',
      }
       const { success ,data} = await getSite(data1)
      if (success) {
        console.log('data.data&&data.data[0].areaName==="新场所"12')
        // if(data.data&&data.data[0].areaName==="新场所"){
        if(data.data&&data.data[0]&&data.data[0].areaName==="新场所"){
          let arr11=data.data
          arr11[0].areaName=this.$t('title.newSite')
          this.data1=arr11
        }else{
          this.data1=data.data
        }
        console.log('getSiteList-this.data1',this.data1)
        sessionStorage.setItem('editItem', JSON.stringify(data.data[0]))
        if(this.searchKey||this.activeIndex!=0){
          if(!this.data1.length){
            sessionStorage.setItem('tableId', '无')
            this.$store.state.tableId = '无'
            sessionStorage.setItem('areaType', '无')
            this.$store.state.areaType = '无'
          }else{
            // this.generateTreeData(this.data1)
            sessionStorage.setItem('tableId', this.data1[0].id)
            this.$store.state.tableId = this.data1[0].id
            sessionStorage.setItem('areaType', this.data1[0].areaType)
            this.$store.state.areaType = this.data1[0].areaType
          }
        }else{
          sessionStorage.setItem('tableId', this.data1[0].id)
          this.$store.state.tableId = this.data1[0].id
          sessionStorage.setItem('areaType', this.data1[0].areaType)
          this.$store.state.areaType = this.data1[0].areaType
        }

        const list=data.data
        let listString = JSON.stringify(list).replace(/"id"/g, '"value"')
        let listStringLabel = listString.replace(/"areaName"/g, '"label"')
        let listStringChildren = listStringLabel.replace(/"children"/g, '"children"')
        var aParse = JSON.parse(listStringChildren)
        if(this.activeIndex===0){
          this.firstItem=aParse[0].value
          console.log('aParsefirstItem',aParse[0].value)
          this.$emit('firstItem',this.firstItem)
        }
        var that=this
        function dG(params) {
        params.forEach(v=>{
          // if(v.value!=firstItem){
          //   if(that.user.type!='0'){
          //     if(v.areaType=='D'&&v.value!=that.user.areaId){
          //       v.disabled=true
          //     }
          //   }
          // }
          if(v.children){
            dG(v.children)
          }else{
            v.children=[]
            // if(that.user.type!='0'){
            //   if(v.areaType=='D'&&v.value!=that.user.areaId){
            //     v.disabled=true
            //   }
            // }
          }
        })
      }
      dG(aParse)
      this.recordTypes=aParse
      } else {
        this.$Message.error(this.$t('staffIndex.stafferror'))
      }
    },
    // 获取上级场所
    async getParent(){
      let editItem= JSON.parse(window.sessionStorage.getItem('editItem'))
      let data1={
        id:editItem.id,
        parentId: editItem.parentId,
      }
      const { success ,data} = await getParentArea(data1)
      if (success) {
        setTimeout(() => {
          this.recordType=data.data
        }, 500);
        
      } else {
        this.$Message.error(this.$t('staffIndex.stafferror'))
      }
    },
    async getData () {
      console.log('gs列表')
      //管理员列表
      const { success, data } = await selectAreaUser({
        page: this.page,
        limit: this.pageSize,
        realName: '',
        roleName: '',
        areaName:'',
        period:'',
        username:'',
        areaId:this.areaId
      })
      let list = []
      let page = 1
      let total = 0
      if (success) {
        list = data.data
        page = data.pageNum || 1
        total = Number(data.count)
      }
      this.list = list
      this.page = page
      this.total = total
    },
    changeSize(e){
      this.pageSize=e;
      this.getData()
    },
    changePage(e){
      this.page=e
      this.getData()
    },
    handleSettingsClick (name, row) {
      switch (name) {
        case 'adminEdit':
          this.showSettingAdmin(row)
          break
        case 'del':
          this.handleDel(row)
          break
      }
    },
    handleChange1 (value) {
      // Change时候赋值给recordType  然后关闭级联下拉框可以选中
      this.recordType = value
      if(value.length>0){       
        this.areaId = value[value.length-1]
      }else{
        this.areaId =''
      }
      this.getData()
    },
    changeIndex(val){
      this.activeIndex=val;
      if(val==2){
        this.$emit('isAreaType','D')
      }else if(val==1){
        this.$emit('isAreaType','G')
      }else if(val==0){
        let areaType=sessionStorage.getItem('storeAreaType')
        this.$emit('isAreaType',areaType)
      }
      this.getSiteList()
    }
  },
}
</script>

<style lang="less" scoped>
.depart-tree {
  float: left;
  // display: inline-block;
  // width: 300px;
  width: 30%;
  max-width: 300px;
  margin-right: @padding-hov;
  min-height: 1070px;

  /deep/ .ivu-tree-title {
    width: 100%;
    width: calc(100% - 21px);
  }
  .newContent{
    .li{
      .title{
        line-height: 36px;
        font-size: 22px;
        font-weight: bold;
        margin-right: 20px;
      }
      .subtitle{
        line-height: 28px;
        font-size: 16px;
        color: #2d8cf0;
        cursor: pointer;
      }
      .dec{
        line-height: 24px;
        font-size: 15px;
        margin-bottom: 10px;
      }
    }
    .tab{
      padding: 16px 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      .item{
        flex: 1;
        margin-right: 10px;
        height: 34px;
        line-height: 34px;
        text-overflow: ellipsis;
        overflow: hidden;
        // font-size: 12px;
        text-align: center;
        border: 1px solid #e9e9e9;
        border-radius: 6px;
        cursor: pointer;
        &.active{
          border: 1px solid #1890ff;
          color:#1890ff;
        }
      }
    }
  }
  
}

.v-transfer-dom{
    /deep/ .ivu-modal-wrap{
      .ivu-modal{
        width: 1100px!important;
      }
    } 
  }  
</style>
